<?php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\Agent;
use App\Models\Mem;

class MemAuth
{
    public function handle(Request $req, Closure $next):Response
    {
        if (strpos($req->header('referer'), 'localhost') > 0) {
            $req->mem = Mem::find(80);
            $req->shopagent = Agent::find($req->mem->aid);
            return $next($req);
        }
        $req->shopagent = Agent::where('code',base64_decode($req->cookie('superbar_unicode')))->first();
        if (empty($req->shopagent)) wxresp(-1,'用户不存在');
        $openid = base64_decode($req->cookie('superbar_memlastopenid'));
        if (empty($openid)) wxresp(-1,'用户不存在。');
        $mem = Mem::where('aid',$req->shopagent->id)->where('openid',$openid)->first();
        if (empty($mem)){
            $mem = new Mem();
            $mem->aid = $req->shopagent->id;
            $mem->openid = $openid;
            $mem->createtime = time();
            $mem->save();
        }
        $req->mem = $mem;
        return $next($req);
    }
}